package ase.assignment.sts.ws.impl;

import java.rmi.RemoteException;

import ase.assignment.sts.api.PortfolioHandler;
import ase.assignment.sts.beans.PortfolioEntity;
import ase.assignment.sts.ws.beans.WSUtil;
import ase.assignment.sts.ws.portfolio.PortfolioPortType;
import ase.assignment.sts.ws.portfolio.PortfolioServiceLocator;

public class PortfolioHandlerWSImpl implements PortfolioHandler {
	private PortfolioPortType portType;

	PortfolioHandlerWSImpl() {
		try {
			portType = new PortfolioServiceLocator().getSTSPortfolio();
		} catch (javax.xml.rpc.ServiceException jre) {
			if (jre.getLinkedCause() != null)
				jre.getLinkedCause().printStackTrace();
		}
	}

	public void create(PortfolioEntity entity) {
		try {
			portType.create(WSUtil.convert(entity));
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public void delete(int porId) {
		try {
			portType.delete(porId);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public PortfolioEntity findById(int porId) {
		try {
			return WSUtil.convert(portType.findById(porId));
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}

	public PortfolioEntity[] getAllPortfolios(String username) {
		try {
			ase.assignment.sts.ws.beans.PortfolioEntity[] entities = portType
					.getAllPortfolios(username);
			if (entities != null) {
				PortfolioEntity[] beans = new PortfolioEntity[entities.length];
				for (int i = 0; i < entities.length; i++) {
					beans[i] = WSUtil.convert(entities[i]);
				}
				return beans;
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void update(PortfolioEntity entity) {
		try {
			portType.update(WSUtil.convert(entity));
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

}
